<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User as UserModel;
use app\common\model\ScoreLog;
use app\common\model\LihuaOrder;
use app\common\library\Sms;
use app\common\model\LihuaWalletOrder;
use app\common\model\LihuaVouchers; //现金抵用券
use app\common\model\LihuaVouchersLog; //现金抵用券使用记录
use app\common\model\general\LihuaCity; //城市模版

use fast\Random;
use think\Validate;
use fast\Http;
use think\Db;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = [
		'login', 
        'mobilelogin', 
        'register', 
		'resetpwd', 
        'third', 
        'sendintegral',
		'wxgetuserinfo', 
        'wxgetuserinfo2',
        'share_vouchers',//扫码获取分享现金券接口
        'share_vouchers2',//扫码获取分享现金券接口
        'vouchers_admin_do',
	];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    //还得定义几个参数
    public static $OK = 0;
    public static $IllegalAesKey     = -41001;
    public static $IllegalIv         = -41002;
    public static $IllegalBuffer     = -41003;
    public static $DecodeBase64Error = -41004;
    
    private $sessionKey;
    private $appid = 'wxcb7a20d43bacdbc2';
    private $appsecret = 'fd7dc1ea861edefc96d6ff3a6ce44224';
    

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    //获取现金抵扣券详情
    public function get_vouchers_info(){
        $sn = $this->request->post('sn', '');//获取扫码信息
        if( !$sn ) $this->error('参数错误');
        //获取用户的有效抵扣券
        $vouchers = LihuaVouchers::where(['sn' => $sn])->find();
        $citys = LihuaCity::where(['id'=>$vouchers['city_id']])->find();
        if($vouchers){
            $status_arr = ['未使用','已使用','已失效'];
            $vouchers['city_name'] = $citys['name'];
            $vouchers['status_txt'] = $status_arr[$vouchers['status']];
            $this->success('OK', $vouchers);
        }else{
            $this->error('现金券不存在');
        }
    }


    //超级管理员处理代金券
    public function vouchers_admin_do(){
        $opt_name = $this->request->request('opt_name', 0);//操作人名称
        $opt_pwd = $this->request->request('opt_pwd', 0);//操作密码
        $opt_id = $this->request->request('opt_id', 0);//代金券ID
        if( !$opt_name || !$opt_pwd || !$opt_id ) $this->error('参数错误');
        if($opt_pwd!='lihua4008') $this->error('参数错误');
        $vouchers = LihuaVouchers::where(['id' => $opt_id])->find();
        if($vouchers['status']==1) $this->error('订单已完成，无需处理');
        $res = LihuaVouchers::update(['status' => 1, 'admin_use_time' => date('Y-m-d H:i:s'), 'admin_status' => 1, "admin_name" => $opt_name, "order_sn"=>"0000000000" ], ['id' => $opt_id]);
        $this->success('OK', $res);
    }



    /***
     * 扫码绑定现金券
     * 扫的是分享者的用户ID
     * 客户端根据扫码信息获取分享者的id信息然后进行后台请求获取有效的券码
     * **/
    public function share_vouchers(){
        //
        $code = $this->request->post('code', '');//获取扫码信息
        if( !$code ) $this->error('参数错误');

        $data_arr = explode('_', $code);
        if($data_arr[0]!="sharevoucher") $this->error('参数错误');

        $user_id = $data_arr[1];
        $day = date('Y-m-d');
        //获取用户的有效抵扣券
        $vouchers = LihuaVouchers::where(['user_id' => $user_id, 'status' => 0, 'order_sn' => '', 'end_date' => ['>=', $day]])->find();
        if($vouchers){
            //如果存在则直接转给别人
            $res = LihuaVouchers::where([ 'id'=> $vouchers['id'] ])->update([ 
                'user_id'       => $this->auth->id,
                'update_time'   => time(),
            ]);
            $datas = [
                "city_id"		=> $vouchers['city_id'],
                "user_id"		=> $vouchers['user_id'],
                "day"			=> date('Y-m-d'),
                "voucher_sn"	=> $vouchers['sn'],
                "order_sn"		=> "",
                "use_type"		=> 4,
                "use_time"		=> date('Y-m-d H:i:s'),
                "create_time"	=> time(),
                "update_time"	=> time(),
            ];
            $ret = LihuaVouchersLog::create($datas);
            $this->success('OK', "成功获取面值".$vouchers['price']."元的现金抵扣券。");
        }else{
            $this->error('暂无现金券可分享');
        }
    }

    /***
     * 扫码绑定现金券
     * 扫的是分享者的用户ID
     * 客户端根据扫码信息获取分享者的id信息然后进行后台请求获取有效的券码
     * **/
    public function share_vouchers2(){
        //
        $code = $this->request->request('code', '');//获取扫码信息
        $city_id = $this->request->request('city_id', 0);//获取扫码信息
        if( !$code ) $this->error('参数错误');

        $data_arr = explode('_', $code);
        if($data_arr[0]!="sharevoucher") $this->error('参数错误');

        $user_id = $data_arr[1];

        $num = (int)$data_arr[2];

        $day = date('Y-m-d');

        $wheres = [
            'user_id' => $user_id, 
            'status' => 0, 
            'order_sn' => '', 
            'end_date' => ['>=', $day]
        ];

        if(!!$city_id){
            $wheres['city_id'] = $city_id;
        }

        //获取用户的有效抵扣券
        $vouchers = LihuaVouchers::where($wheres)->limit($num)->select();
        if($vouchers){
            
            $vouchers_arr = collection($vouchers)->toArray();
            $vouchers_ids = array_column($vouchers_arr, 'id');

            try {
                //开始事务
                Db::startTrans();
                //如果存在则直接转给别人
                $res = LihuaVouchers::where([ 'id'=> ['IN', $vouchers_ids] ])->update([ 
                    'user_id'       => $this->auth->id,
                    'update_time'   => time(),
                ]);
                $s = LihuaVouchers::getLastSql();
                foreach ($vouchers_arr as $k => $v) {
                    $datas = [
                        "city_id"		=> $v['city_id'],
                        "user_id"		=> $v['user_id'],
                        "day"			=> date('Y-m-d'),
                        "voucher_sn"	=> $v['sn'],
                        "order_sn"		=> "",
                        "use_type"		=> 4,
                        "use_time"		=> date('Y-m-d H:i:s'),
                        "create_time"	=> time(),
                        "update_time"	=> time(),
                    ];
                    $ret = LihuaVouchersLog::create($datas);
                }
                Db::commit();
            } catch (\Throwable $th) {
                Db::rollback();
                $this->error('获取分享现金券失败，请重新尝试');
            }
            $this->success('OK', "成功获取".$num."张现金抵扣券。。");
        }else{
            $this->error('暂无现金券可分享');
        }
    }

    /**
     * 现金抵扣券使用记录
     * **/
    public function voucher_log(){
        $city_id   = (int)$this->request->post('city_id');
        if (!$city_id) $this->error('参数错误');
        
        $page      = max(1, (int)$this->request->post('page'));
        $page_size = (int)$this->request->post('page_size') ? : 20;
        $data      = [
            'page'       => $page,
            'total'      => 0,
            'page_size'  => $page_size,
            'total_page' => 0,
            'list'       => []
        ];

        $where['user_id'] = $this->auth->id;
        $where['city_id'] = ['in', [0, $city_id]];
        $total = LihuaVouchersLog::where($where)->count();
        
        if ($total) {
            $data['total']      = $total;
            $data['total_page'] = ceil($total/$page_size);
            $list = LihuaVouchersLog::where($where)
                ->order('id', 'desc')->page($page, $page_size)->select();
            if(!!$list){
                $use_type_arr = ['','领券成功','线上消费抵扣','线下消费抵扣','分享赠送'];
                foreach ($list as $k => $v) {
                    $list[$k]['use_type_txt'] = $use_type_arr[(int)$v['use_type']];
                }
            }
            $data['list'] = $list;
        }
        $this->success('OK', $data);
    }


    public function user_vouchers(){
        $city_id   = (int)$this->request->post('city_id');
        if (!$city_id) $this->error('参数错误');
        // $type      = (int)$this->request->post('type', 1);
        $page      = max(1, (int)$this->request->post('page'));
        $page_size = (int)$this->request->post('page_size') ? : 20;
        $data      = [
            'page'       => $page,
            'total'      => 0,
            'page_size'  => $page_size,
            'total_page' => 0,
            'list'       => []
        ];

        $day = date('Y-m-d');

        $where['user_id'] = $this->auth->id;
        $where['city_id'] = ['in', [0, $city_id]];
        $where['end_date'] = ['>=', $day];
		
        // if ($type == 1) {
        //     $where['status'] = 0;
        // } else {
        //     $where['status'] = ['>', 0];
        // }
        $where['status'] = 0;
        $total = LihuaVouchers::where($where)->count();
        // $s = LihuaVouchers::getLastSql();
        if ($total) {
            $data['total']      = $total;
            $data['total_page'] = ceil($total/$page_size);
            $list = LihuaVouchers::where($where)
                ->order('id', 'desc')->page($page, $page_size)->select();
            $data['list'] = $list;
        }
        $this->success('OK', $data);
    }

    /***
     * 获取用户的可用现金券数量
     * **/
    public function getuservouchers_count(){
        $user_id  = $this->auth->id;
        $city_id = $this->request->request('city_id', 0);
        $data = [];
        $status_text_arr = ['未使用', '已使用', '已失效'];

        $where = [];
        $day = date('Y-m-d');
        $where['user_id'] = $this->auth->id;
        $where['status'] = 0;
        $where['city_id'] = ['in', [0, $city_id]];
        $where['end_date'] = ['>=', $day];

        $list = LihuaVouchers::where($where)->select();
        foreach ($list as $k => $v) {
            $list[$k]['status_text'] = $status_text_arr[(int)$v['status']];
        }
        if(!!$list) $data = count($list);
        $this->success('OK', $data);
    }

    /***
     * 获取用户的可用现金券
     * **/
    public function getuservouchers(){
        $user_id  = $this->auth->id;
        $city_id = $this->request->request('city_id', 0);
        $data = [];
        $status_text_arr = ['未使用', '已使用', '已失效'];
        
        $where = [];
        $day = date('Y-m-d');
        $where['user_id'] = $this->auth->id;
        $where['status'] = 0;
        $where['city_id'] = ['in', [0, $city_id]];
        $where['end_date'] = ['>=', $day];
        $where['type'] = ['<=', 1];

        $list = LihuaVouchers::where($where)->select();
        foreach ($list as $k => $v) {
            $list[$k]['status_text'] = $status_text_arr[(int)$v['status']];
        }
        if(!!$list) $data = $list;
        $this->success('OK', $data);
    }

    /***
     * 用户绑定现金券
     * **/
    public function bindvouchers(){
        $user_id  = $this->auth->id;
        $sn = $this->request->request('sn', "");
        $sn = strtoupper($sn);
        $vouchers = LihuaVouchers::where(['sn'=> $sn, 'status'=> 0 ])->find();
        if($vouchers){
            if(!!$vouchers['user_id']) $this->error('该现金券已经被绑定');            
            $res = LihuaVouchers::where([ 'sn'=>$sn ])->update([ 'user_id'=>$user_id ]);
            $this->success('OK', $res);
        }else{
            $this->error('券码无效，请输入正确的券码');
        }
    }

	/**
	 * 订单派发积分
	 * 订单积分根据商品价格来分发
	 */
	public function sendintegral()
    {
        $order_sn  = $this->request->request('order_sn');
        $integral = $this->request->request('integral');
        $key = $this->request->request('key');
		if (!$order_sn || !$integral || !$key) $this->error('参数错误');
		if ($key!= 'lihua4008Lihua')$this->error('Key值不对');

        //添加redis避免重复扣款
		$redis = new \Redis();
        $redis->connect('1.13.13.216', 6379);
		$redis->auth('jwhklk');
        $redis->incr('integral_'.$order_sn);
        $redis->expire('integral_'.$order_sn, 5);
        if($redis->get('integral_'.$order_sn)>1){
			$this->error('积分发送重复调用');
		}

		//判断订单积分是否已经赠送
        $count = ScoreLog::where(array('order_sn'=>$order_sn))->count();
        if($count>0){
            $this->error('该订单已经赠送过积分');
        }
        //查询订单详情
        $order = LihuaOrder::where(array('sn'=>$order_sn))->find();
        //发送积分
        $memo = $order['platform'] . '下单成功';
        $sendscore = UserModel::score(intval($integral), $order['user_id'], $memo, $order['sn']);
        if($sendscore){
            $this->success('积分加入成功');
        }else{
            $this->error('无法查询到订单用户');
        }
    }
	/**
	 * 检查手机号是否已经注册过账号
	 */
	public function checkphone()
	{
	    $phone  = $this->request->request('phone');
		if (!$phone) $this->error('参数错误');
		if (!Validate::regex($phone, "^1\d{10}$"))   $this->error('手机号格式错误');
		//判断订单积分是否已经赠送
	    $count = UserModel::where(array('mobile'=>$phone))->count();
	    if($count>0){
	        $this->error('该手机号已经注册过账号');
	    }else{
			$this->success('返回成功');
		}
	}
	/**
	 * 绑定手机号
	 */
	public function bindphone()
	{
	    $mobile  = $this->request->request('mobile');
	    $user_id  = $this->request->request('user_id');
		$captcha   = $this->request->request('captcha');
		if (!$mobile || !$user_id || !$captcha) $this->error('参数错误');
		
		if (!Validate::regex($mobile, "^1\d{10}$"))   $this->error('手机号格式错误');
		if (!Sms::check($mobile, $captcha, 'login')) $this->error('验证码错误');
		
		//判断订单积分是否已经赠送
	    $bindphone = UserModel::update(['mobile' => $mobile], ['id' => $user_id]);
	    if($bindphone){
	        $this->success('绑定手机号成功');
	    }else{
			$this->error('绑定失败:'.$this->auth->getError());
		}
	}
	
	/**
	 * 获取用户当前城市的钱包余额
	 * phone cityname
	 */
	public function getusermoney()
	{
		$phone = $this->request->request("phone");
		$cityname = $this->request->request("cityname");
		if (!$cityname || !$phone) $this->error('参数错误');
		if (!Validate::regex($phone, "^1\d{10}$"))   $this->error('手机号格式错误');
		$post_data = array(
		    'cityname' => $cityname,
			'phone' => $phone
		);
		$ret = Http::post("http://qianbao.lihua.com/api/wallet/getusermoney", $post_data);
		$res = json_decode($ret, true);
        
		if($res['code']==0){
			$this->error($res['msg']);
		}else{
			$this->success('返回成功', $res['data']);
		}
	}
	/**
	 * 根据code获取解密用户openid和uniid
	 */
	public function wxgetuserinfo(){
		$js_code = $this->request->request('js_code');
		$url = 'https://api.weixin.qq.com/sns/jscode2session';
		$params = [
			'appid'   		=> 'wxcb7a20d43bacdbc2',
			'secret'  		=> "fd7dc1ea861edefc96d6ff3a6ce44224", //应用secret
			'js_code' 		=> $js_code,
			'grant_type' 	=> 'authorization_code',
		];
		$ret = Http::post($url, $params);
		$result = json_decode($ret, true);
		$this->success('返回成功', $result);
    }

    //解密方式获取用户信息
    public function wxgetuserinfo2()
    {
        $js_code = $this->request->request('js_code');
        $encryptedData = $this->request->request('encryptedData');
        $iv = $this->request->request('iv');
        if (!$js_code || !$encryptedData || !$iv) $this->error('参数错误');

        $api = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->appsecret}&js_code={$js_code}&grant_type=authorization_code";
        $res = Http::get($api);
        if ($res) {
            $arr = json_decode($res, true);
            if (isset($arr['session_key'])) {
                $this->sessionKey = $arr['session_key'];
                $errCode = $this->decryptData($encryptedData, $iv, $data);
                if ($errCode == 0) {
                    $ret = json_decode($data, true);
                    $this->success('OK', $ret);
                } else {
                    $this->error($errCode);
                }
            } else {
                $this->error($res);
            }
        }
        $this->error('未请求到数据');
    }

    /**
     * 检验数据的真实性，并且获取解密后的明文
     *
     * @ApiInternal
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     * @return int 成功0，失败返回对应的错误码
     */
    public function decryptData( $encryptedData, $iv, &$data )
    {
        if (strlen($this->sessionKey) != 24) return self::$IllegalAesKey;

        $aesKey = base64_decode($this->sessionKey);

        if (strlen($iv) != 24) return self::$IllegalIv;

        $aesIV     = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result    = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj   = json_decode($result);

        if ($dataObj == NULL) return self::$IllegalBuffer;
        if ($dataObj->watermark->appid != $this->appid) return self::$IllegalBuffer;

        $data = $result;
        return self::$OK;
    }


	/**
	 * 充值钱包支付密码
	 * mobile newpassword
	 */
	public function changepaypwd(){
		$mobile = $this->request->request("mobile");
		$newpwd = $this->request->request("newpwd");
		$captcha = $this->request->request("captcha");
		if (!$mobile || !$newpwd || !$captcha) $this->error('参数错误');
		if (!Validate::regex($mobile, "^1\d{10}$"))   $this->error('手机号格式错误');
		if (!Sms::check($mobile, $captcha, 'login')) $this->error('验证码错误');
		if (mb_strlen($newpwd) < 6) $this->error('密码长度至少6位');
		$post_data = array(
		    'mobile' => $mobile,
			'newpassword' => $newpwd
		);
		$ret = Http::post("http://qianbao.lihua.com/api/user/resetpwd", $post_data);
		$res = json_decode($ret, true);
		if($res['code']==0){
			$this->error($res['msg']);
		}else{
			$this->success('返回成功', $res['data']);
		}
	}
	
	/**
	 * 获取当前城市所包含的钱包充值活动 wallet_actlist
	 */
	public function wallet_actlist()
    {
        $cityname = $this->request->request("cityname");
        $user = $this->auth->getUserinfo();
		if (!$cityname) $this->error('参数错误');
		$post_data = array(
            'cityname' => $cityname,
            'user_id' => $user['id'],
		);
		$act_list = Http::post("http://qianbao.lihua.com/api/wallet/activitylist", $post_data);
		$res = json_decode($act_list, true);
		if($res['code']==0){
			$this->error($res['msg']);
		}
		if($res['code']==1){
            //常州地区88元到账100只允许充值一次
            if($cityname=='常州'){
                $count = LihuaWalletOrder::where(['user_id'=> $user['id'], 'money'=> '88.00', 'status'=> '2'])->count();
                $s = LihuaWalletOrder::getLastSql();
                if($count>0){
                    $act_list_arr = explode(',', $res['data']['rulelist']);
                    $new_act_str = '';
                    foreach ($act_list_arr as $k => $v) {
                        if($v!='88~100'){
                            if($new_act_str == ''){
                                $new_act_str = $v;
                            }else{
                                $new_act_str = $new_act_str . ',' . $v;
                            }
                        }
                    }
                    $res['data']['rulelist'] = $new_act_str;
                }
            }

			$this->success('返回成功', $res['data']);
		}
    }
    
	/**
	 * 会员充值钱包,生成充值订单
	 */
	public function createwalletorder(){
		$money  = $this->request->request('money'); //支付金额
		$getmoney = $this->request->request('getmoney');//到账金额
		$actid = $this->request->request('actid');//充值活动id
		$plt = $this->request->request('plt');
		$city_id = $this->request->request('city_id');
		$user_id = $this->request->request('user_id');
        $mobile = $this->request->request('mobile');
        $paytype = (int)$this->request->request('paytype', 2);
		if (!in_array($plt, ['app', 'xcx'])) $this->error('非法操作');
		if (!$money || !$getmoney || !$actid) $this->error('参数错误');
		//这里去请求钱包系统是否能生成订单
		$post_data = array(
		    'money' => $money,
		    'getmoney' => $getmoney,
		    'actid' => $actid
		);

        //常州地区88元到账100只允许充值一次
        if($city_id=='3' && $money=='88.00'){
            $count = LihuaWalletOrder::where(['user_id'=> $user_id, 'money'=> '88.00', 'status'=> '2'])->count();
            if($count>0){
                $this->error('常州地区88元充值机会每个用户只能享受一次');
            }
        }

		$userinfo = Http::post("http://qianbao.lihua.com/api/wallet/addorderchk", $post_data);
		$res = json_decode($userinfo, true);
		if($res['code']==0){
			$this->error($res['msg']);
		}
		if($res['code']==1){
			//创建充值订单
			$machine = 5;
            $IdWorker = new \app\common\model\IdWorker($machine);
            $sn =  (strval($IdWorker->nextId()) . mt_rand(1, 9999));
			$data = [
			    'money' => $money,
			    'getmoney' => $getmoney,
			    'status' => 1,
			    'platform' => $plt,
			    'sn' => $sn,
			    'city_id' => $city_id,
				'user_id' => $user_id,
				'mobile' => $mobile,
                'actid' => $actid,
                'pay_type' => $paytype
			];
            $walletOrder = LihuaWalletOrder::create($data);
            if($walletOrder){
                $this->success('订单创建成功', $walletOrder);
            }else{
                $this->error($this->auth->getError());
            }
		}
	}
	
	/**
	 * 获取用户充值列表 
	 */
	public function userprepaidlist(){
		$cityname  = $this->request->request('cityname'); //支付金额
		$mobile = $this->request->request('mobile');//手机号
		if (!$mobile || !$cityname) $this->error('参数错误');
		if (!Validate::regex($mobile, "^1\d{10}$"))   $this->error('手机号格式错误');
		//这里去请求钱包系统是否能生成订单
		$post_data = array(
		    'cityname' => $cityname,
		    'phone' => $mobile,
		);
		$res = Http::post("http://qianbao.lihua.com/api/wallet/userprepaidlist", $post_data);
		$list = json_decode($res, true);
		if($list['code']==0){
			$this->error($list['msg']);
		}
		if($list['code']==1){
	        $this->success('返回成功', ['list' => $list['data']]);
		}
	}
	
	/**
	 * 获取用户充值列表 
	 */
	public function usershoppinglist(){
		$cityname  = $this->request->request('cityname'); //支付金额
		$mobile = $this->request->request('mobile');//手机号
		if (!$mobile || !$cityname) $this->error('参数错误');
		if (!Validate::regex($mobile, "^1\d{10}$"))   $this->error('手机号格式错误');
		//这里去请求钱包系统是否能生成订单
		$post_data = array(
		    'cityname' => $cityname,
		    'phone' => $mobile,
		);
		$res = Http::post("http://qianbao.lihua.com/api/wallet/usershoppinglist", $post_data);
		$list = json_decode($res, true);
		if($list['code']==0){
			$this->error($list['msg']);
		}
		if($list['code']==1){
		    $this->success('返回成功', ['list' => $list['data']]);
		}
	}
	
	/**
     * 会员登录
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="account", type="string", required=true, description="用户名或手机号")
     * @ApiParams   (name="password", type="string", required=true, description="密码")
     * @ApiReturn   ({"code":1,"msg":"登录成功","time":"1569515572","data":{}})
     */
    public function login()
    {
        /*
         * 1、先要判断是能直接登录成功
         * 2、不能直接登录成功的用户需要调用来系统的是否能登录成功
         * */
        $account  = $this->request->request('account');
        $password = $this->request->request('password');
        $plt = $this->request->request('plt');
        if (!$account || !$password) $this->error('参数错误');
        $ret = $this->auth->login($account, $password);
        $users = UserModel::where(['mobile'=> $account])->whereOr(['username'=> $account])->find();
        if ($ret) {
            //登录成功
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success('登录成功', $data);
        } else {
            //登录失败
            $post_data = array(
                'account' => $account,
                'password' => $password,
                'plt' => $plt,
            );
            $userinfo = Http::post("https://api.lihua.com/index/User/newSysLogin", $post_data);
            $userinfoData = json_decode($userinfo,true);
            if($userinfoData['status']==0){
				$userData = $userinfoData['data'];
				$oldUserid = $userData['id'];
                //登录成功，同步用户数据
                $mobile = Validate::regex($account, '/^1\d{10}$/') ?  $account: '';
                if($mobile==''){
                    $mobile = Validate::regex($userData['tel'], '/^1\d{10}$/') ?  $userData['tel']: '';
                }
                $ret = false;
                //判断用户是否存在，如果存在，则不能注册
                $haveAccount = UserModel::getByUsername($account);
                $haveMobile = UserModel::getByMobile($account);
                if($haveAccount || $haveMobile){
                    // $this->error('账号密码错误');
                    $salt = Random::alnum();
                    $newpwd = $this->auth->getEncryptPassword($password, $salt);
                    $ret_changepwd = UserModel::update(['password' => $newpwd, 'salt' => $salt], ['username|mobile' => $account]);
                    if ($ret_changepwd) {
                        $ret = $this->auth->login($account, $password);
                    } else {
                        $this->error($this->auth->getError());
                    }
                }else{
                    $reg_username = $userData['account'];
                    if($mobile==$userData['account'] || Validate::regex($userData['account'], '/^1\d{10}$/')){
                        $reg_username = substr(md5($userData['account']), mt_rand(1,15), 10);
                    }
                    //注册新用户
                    $ret = $this->auth->register($reg_username, $password, '', $mobile, []);
                }
                if ($ret) {
                    //登录成功
                    $userid = $this->auth->id;
                    //跟新积分数据
                    $clearScore = false;
                    // if($userData['totalIntegral']>0){
                    //     $ret_update = UserModel::score(intval($userData['totalIntegral']), $userid, '老系统转移积分至新系统');
                    //     //如果更新积分成功
                    //     if($ret_update){
                    //         //将老系统积分清零 clearUserIntegral
                    //         $post_clear_score = array(
                    //             'userId' => $oldUserid
                    //         );
                    //         $clearScoreData = Http::post("https://api.lihua.com/index/User/clearUserIntegral", $post_clear_score);
                    //         $clearScoreData = json_decode($clearScoreData,true);
                    //         if($clearScoreData["status"]==0 && $clearScoreData["data"]==1){
                    //             $clearScore = true;
                    //         }
                    //     }
                    // }
                    $data = $this->auth->getUserinfo();
                    $data['clearScore'] = $clearScore;
                    $data['score'] = $userData['totalIntegral']>0 ? $userData['totalIntegral'] : $data['score'];
                    $this->success('登录成功', ['userinfo'=>$data]);
                } else {
                    $this->error($this->auth->getError());
                }
            }else{
				//老系统也登录失败
                if(!!$users) {
                    $this->error("密码错误");
                }else{
                    $this->error($userinfoData['message']);
                }
            }
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams   (name="captcha", type="string", required=true, description="验证码")
     * @ApiReturn   ({"code":1,"msg":"登录成功","time":"1569515572","data":{}})
     */
    public function mobilelogin()
    {
        $mobile  = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) $this->error('参数错误');

        if (!Validate::regex($mobile, "^1\d{10}$")) $this->error('手机号格式错误');
        if (!Sms::check($mobile, $captcha, 'login')) $this->error('验证码错误');

        $user = UserModel::getByMobile($mobile);
        $old_total_integral = 0;    //老系统用户积分
        $oldUserid = 0;       //老系统用户id
        $clearScore = false;   //是否有清除老系统积分的操作
        if ($user) {
            if ($user->status != 'normal') $this->error(__('Account is locked'));
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            /* 注册之前需要获取老系统用户信息  根据手机号获取来系统用户数据
             * 老用户的密码数据无法获取，只能重新生成
             * **/
            $payload = array('phone' => $mobile);
            $getUserInfo = Http::post("https://api.lihua.com/index/User/getUserInfoByPhone", $payload);
            $getUserInfo = json_decode($getUserInfo,true);
            if($getUserInfo['status']==0){
                $old_total_integral = $getUserInfo['data']['total_integral'];
                $oldUserid = $getUserInfo['data']['id'];
            }
            $username = substr(md5($mobile), mt_rand(1,15), 10);
            $ret = $this->auth->register($username, Random::alnum(), '', $mobile, []);
            //跟新用户积分数据
            // if($old_total_integral>0 && $ret){
            //     //$ret_update = UserModel::update([ 'score' => $old_total_integral ], ['id' => $this->auth->id]);
            //     $ret_update = UserModel::score(intval($old_total_integral), $this->auth->id, '老系统转移积分至新系统');
            //     //如果更新积分成功
            //     if($ret_update){
            //         //将老系统积分清零 clearUserIntegral
            //         $post_clear_score = array(
            //             'userId' => $oldUserid
            //         );
            //         $clearScoreData = Http::post("https://api.lihua.com/index/User/clearUserIntegral", $post_clear_score);
            //         $clearScoreData = json_decode($clearScoreData,true);
            //         if($clearScoreData["status"]==0 && $clearScoreData["data"]==1){
            //             $clearScore = true;
            //         }
            //     }
            // }
        }
        if ($ret) {
            Sms::flush($mobile, 'login');
            $data = $this->auth->getUserinfo();
            $data['clearScore'] = $clearScore;
            $data['score'] = $old_total_integral>0 ? $old_total_integral : $data['score'];
            $this->success('登录成功', ['userinfo' => $data]);
        } else {
            $this->error($this->auth->getError());
        }
    }
    
	/**
	 * 根据订单id获取充值订单详情
	 */
	public function getwalletorder()
	{
		$sn  = $this->request->request('sn');
		if(!$sn) $this->error('参数错误');
		$ret = LihuaWalletOrder::where('sn', $sn)->find();
		if ($ret){
			$this->success('返回成功', $ret);
		}else{
			$this->error('订单不存在');
		} 
		
	}

    /**
     * 注册会员
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="username", type="string", required=true, description="用户名")
     * @ApiParams   (name="password", type="string", required=true, description="密码")
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号")
     * @ApiReturn   ({"code":1,"msg":"注册成功","time":"1569515572","data":{}})
     */
    public function register()
    {
        $username = $this->request->request('username');
        $password = $this->request->request('password');
        $mobile   = $this->request->request('mobile');
        if (!$username || !$password) $this->error('参数错误');
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) $this->error('手机号格式错误');
        $ret = $this->auth->register($username, $password, '', $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success('注册成功', $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 单独获取老系统用户数据
     * 如果有积分，则添加进来，并且将老系统积分清零
     * @ApiMethod   (POST)
     */
    public function getOldUserIntegral()
    {
        $username = $this->request->request('username');
        $userid = $this->request->request('userid');
        if (!$username || !$userid) $this->error('参数错误');
        $old_total_integral = 0;
        $oldUserid = 0;
        $clearScore = false;
        $payload = array('phone' => $username);
        $getUserInfo = Http::post("https://api.lihua.com/index/User/getUserInfoByPhone", $payload);
        $getUserInfo = json_decode($getUserInfo,true);
        if($getUserInfo['status']==0){
            $old_total_integral = $getUserInfo['data']['total_integral'];
            $oldUserid = $getUserInfo['data']['id'];
        }
        if($old_total_integral>0){
            $ret_update = UserModel::update([ 'score' => $old_total_integral ], ['id' => $userid]);
            //如果更新积分成功
            if($ret_update){
                //将老系统积分清零 clearUserIntegral
                $post_clear_score = array(
                    'userId' => $oldUserid
                );
                $clearScoreData = Http::post("https://api.lihua.com/index/User/clearUserIntegral", $post_clear_score);
                $clearScoreData = json_decode($clearScoreData,true);
                if($clearScoreData["status"]==0 && $clearScoreData["data"]==1){
                    $clearScore = true;
                }
            }
        }
        $data = array(
            'integral' => $old_total_integral,
            'user_id' => $oldUserid,
        );
		$this->success('成功返回', $data);
    }

    /**
     * 单独获取老系统用户数据
     * 如果有积分，则添加进来，并且将老系统积分清零
     * @ApiMethod   (POST)
     */
    public function moveOldUserIntegral()
    {
        $username = $this->request->request('username');
        if (!$username) $this->error('参数错误');
        $old_total_integral = 0;
        $oldUserid = 0;
        $payload = array('phone' => $username);
        $getUserInfo = Http::post("https://api.lihua.com/index/User/getUserInfoByPhone", $payload);
        $getUserInfo = json_decode($getUserInfo,true);
        if($getUserInfo['status']==0){
            $old_total_integral = $getUserInfo['data']['total_integral'];
            $oldUserid = $getUserInfo['data']['id'];
        }
    }

    /**
     * 注销登录
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiReturn   ({"code":1,"msg":"注销成功","time":"1569515572","data":{}})
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success('注销成功');
    }

    /**
     * 修改用户名
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="username", type="string", required=true, description="用户名")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1569515572","data":{"username":"hardy"}})
     */
    public function changeusername()
    {
        $username = $this->request->post('username');
        if ($username) {
            if (!Validate::is($username, 'alphaNum')) $this->error('用户名只允许字母及数字');
            if (mb_strlen($username) > 30) $this->error('用户名只允许30字以内');
            $exists = UserModel::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) $this->error('用户名已存在');

            UserModel::update(['username' => $username], ['id' => $this->auth->id]);
            $this->success('OK', ['username' => $username]);
        }
        $this->error('修改失败');
    }

    /**
     * 修改昵称
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="nickname", type="string", required=true, description="昵称")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1569515572","data":{"nickname":"大帝"}})
     */
    public function changenickname()
    {
        $nickname = $this->request->post('nickname');
        if ($nickname) {
            if (!Validate::is($nickname, 'chsAlphaNum')) $this->error('昵称只允许汉字、字母和数字');
            if (mb_strlen($nickname) > 15) $this->error('昵称只允许15字以内');

            UserModel::update(['nickname' => $nickname], ['id' => $this->auth->id]);
            $this->success('OK', ['nickname' => $nickname]);
        }
        $this->error('修改失败');
    }

    /**
     * 修改手机号
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams   (name="captcha", type="string", required=true, description="验证码")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1569515572","data":{"mobile":"13961259888"}})
     */
    public function changemobile()
    {
        $user    = $this->auth->getUser();
        $mobile  = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) $this->error('参数错误');

        if (!Validate::regex($mobile, "^1\d{10}$")) $this->error('手机号格式错误');

        $exists = UserModel::where('mobile', $mobile)->where('id', '<>', $user->id)->find();
        if ($exists) $this->error('手机号已存在');

        $res = Sms::check($mobile, $captcha, 'changemobile');
        if (!$res) $this->error('验证码错误');

        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success('OK', ['mobile' => $mobile]);
    }

	/**
	 * 检查手机号是否已经开通了钱包账号 
	 */
	public function checkwalletmobile(){
		$mobile = $this->request->request("mobile");
		if (!$mobile) $this->error('参数错误');
		if (!Validate::regex($mobile, "^1\d{10}$"))   $this->error('手机号格式错误');
		$post_data = array(
		    'phone' => $mobile
		);
		$ret = Http::post("http://qianbao.lihua.com/api/wallet/getUserInfo", $post_data);
		$res = json_decode($ret, true);
		if($res['code']==0){
			$this->error($res['msg']);
		}
		if($res['code']==1){
			$this->success('返回成功', array('id'=>$res['data']['id']));
		}
	}
    /**
     * 设置密码
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="newpwd", type="string", required=true, description="新密码")
     * @ApiParams   (name="confirmpwd", type="string", required=true, description="确认密码")
     * @ApiReturn   ({"code":1,"msg":"设置密码成功","time":"1569515572","data":{}})
     */
    public function changepwd()
    {
        $newpwd  = $this->request->post("newpwd");
        $confirmpwd  = $this->request->post("confirmpwd");
        if (!$newpwd || !$confirmpwd) $this->error('参数错误');

        if ($newpwd != $confirmpwd) $this->error('两次密码不一致');
        if (mb_strlen($newpwd) < 6) $this->error('密码长度至少6位');

        $ret = $this->auth->changepwd($newpwd, '', true);
        if ($ret) {
            $this->success('设置密码成功');
        } else {
            $this->error($this->auth->getError());
        }
    }
	
	//开通某个手机号的丽华钱包功能
	public function openwallet()
	{
	    $mobile  = $this->request->post("mobile");
	    $username  = $this->request->post("username");
	    $pwd  = $this->request->post("pwd");
	    $captcha  = $this->request->post("captcha");
	    if (!$mobile || !$pwd || !$captcha || !$username ) $this->error('参数错误');
		if (!Validate::regex($mobile, "^1\d{10}$"))   $this->error('手机号格式错误');
		
	    if (mb_strlen($pwd) < 6) $this->error('密码长度至少6位');
		$ret = Sms::check($mobile, $captcha, 'login');
		if (!$ret) $this->error('验证码错误');
		$post_data = array(
		    'phone' => $mobile
		);
		$ret1 = Http::post("http://qianbao.lihua.com/api/wallet/getUserInfo", $post_data);
		$res = json_decode($ret1, true);
		if($res['code']==0){
			$post_data = array(
			    'username'  => $username,
			    'password'  => $pwd,
			    'mobile'    => $mobile
			);
			$result = Http::post("http://qianbao.lihua.com/api/user/register", $post_data);
			$res2 = json_decode($result, true);
			if($res2['code']==0){
				
			}else{
				$this->success('返回成功', $res2['data']['userinfo']);
			}
		}else{
			$this->success('返回成功', $res['data']);
		}
		
	}

    /**
     * 重置密码
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams   (name="newpwd", type="string", required=true, description="新密码")
     * @ApiParams   (name="captcha", type="string", required=true, description="验证码")
     * @ApiReturn   ({"code":1,"msg":"重置密码成功","time":"1569515572","data":{}})
     */
    public function resetpwd()
    {
        $mobile  = $this->request->request("mobile");
        $newpwd  = $this->request->request("newpwd");
        $captcha = $this->request->request("captcha");
        if (!$newpwd || !$captcha) $this->error('参数错误');

        if (!Validate::regex($mobile, "^1\d{10}$")) $this->error('手机号格式错误');
        if (mb_strlen($newpwd) < 6) $this->error('密码长度至少6位');

        $user = UserModel::getByMobile($mobile);
        if (!$user) $this->error('用户不存在');

        $ret = Sms::check($mobile, $captcha, 'login');
        if (!$ret) $this->error('验证码错误');

        Sms::flush($mobile, 'login');

        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpwd, '', true);
        if ($ret) {
            $this->success('重置密码成功');
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 第三方登录
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="platform", type="string", required=true, description="平台名称")
     * @ApiParams   (name="code", type="string", required=true, description="Code码")
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }
}